//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by Perpetual Motion Interactive Systems Inc. ( http://www.perpetualmotion.ca )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using DotNetNuke.Services.Analytics;
namespace DotNetNuke.HttpModules.Analytics
{
	public class AnalyticsModule : IHttpModule
	{
		public string ModuleName {
			get { return "AnalyticsModule"; }
		}
		public void Init(HttpApplication application)
		{
			application.PreRequestHandlerExecute += this.OnPreRequestHandlerExecute;
		}
		private void OnPreRequestHandlerExecute(object sender, EventArgs e)
		{
			try {
				HttpApplication app = (HttpApplication)sender;
				HttpRequest Request = app.Request;
				if (Request.Url.LocalPath.ToLower().EndsWith("install.aspx") || Request.Url.LocalPath.ToLower().EndsWith("installwizard.aspx")) {
					return;
				}
				if (Request.Url.LocalPath.ToLower().EndsWith(".aspx") == false && Request.Url.LocalPath.ToLower().EndsWith(".asmx") == false && Request.Url.LocalPath.ToLower().EndsWith(".ashx") == false) {
					return;
				}
				if (HttpContext.Current != null) {
					HttpContext context = HttpContext.Current;
					if ((context == null))
						return;
					DotNetNuke.Framework.CDefault page = context.Handler as DotNetNuke.Framework.CDefault;
					if ((page == null))
						return;
					page.Load += OnPageLoad;
				}
			} catch (Exception ex) {
				Services.Log.EventLog.EventLogController objEventLog = new Services.Log.EventLog.EventLogController();
				Services.Log.EventLog.LogInfo objEventLogInfo = new Services.Log.EventLog.LogInfo();
				objEventLogInfo.AddProperty("Analytics.AnalyticsModule", "OnPreRequestHandlerExecute");
				objEventLogInfo.AddProperty("ExceptionMessage", ex.Message);
				objEventLogInfo.LogTypeKey = Services.Log.EventLog.EventLogController.EventLogType.HOST_ALERT.ToString();
				objEventLog.AddLog(objEventLogInfo);
			}
		}
		private void OnPageLoad(object sender, EventArgs e)
		{
			try {
				Config.AnalyticsEngineCollection analyticsEngines = Config.AnalyticsEngineConfiguration.GetConfig().AnalyticsEngines;
				if (analyticsEngines == null || analyticsEngines.Count == 0)
					return;
				Page page = (Page)sender;
				if ((page == null))
					return;
				foreach (Config.AnalyticsEngine engine in analyticsEngines) {
					if ((!String.IsNullOrEmpty(engine.ElementId))) {
						AnalyticsEngineBase objEngine = null;
						if ((!String.IsNullOrEmpty(engine.EngineType))) {
							Type engineType = Type.GetType(engine.EngineType);
							objEngine = (AnalyticsEngineBase)Activator.CreateInstance(engineType);
						} else {
							objEngine = (AnalyticsEngineBase)new DotNetNuke.Services.Analytics.GenericAnalyticsEngine();
						}
						if (objEngine != null) {
							string script = engine.ScriptTemplate;
							if ((!String.IsNullOrEmpty(script))) {
								script = objEngine.RenderScript(script);
								if ((!String.IsNullOrEmpty(script))) {
									HtmlContainerControl element = (HtmlContainerControl)page.FindControl(engine.ElementId);
									if (element != null) {
										LiteralControl scriptControl = new LiteralControl();
										scriptControl.Text = script;
										if (engine.InjectTop) {
											element.Controls.AddAt(0, scriptControl);
										} else {
											element.Controls.Add(scriptControl);
										}
									}
								}
							}
						}
					}
				}
			} catch (Exception ex) {
				Services.Log.EventLog.EventLogController objEventLog = new Services.Log.EventLog.EventLogController();
				Services.Log.EventLog.LogInfo objEventLogInfo = new Services.Log.EventLog.LogInfo();
				objEventLogInfo.AddProperty("Analytics.AnalyticsModule", "OnPageLoad");
				objEventLogInfo.AddProperty("ExceptionMessage", ex.Message);
				objEventLogInfo.LogTypeKey = Services.Log.EventLog.EventLogController.EventLogType.HOST_ALERT.ToString();
				objEventLog.AddLog(objEventLogInfo);
			}
		}
		public void Dispose()
		{
		}
	}
}
